package com.atguigu.worktest;

import com.atguigu.bean.UserBehavior;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;

public class Flink01_PV {
    public static void main(String[] args) {
        Configuration configuration = new Configuration();
        configuration.setInteger("rest.port", 10000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(configuration);
        env.setParallelism(1);

        //读取数据源
        DataStreamSource<String> ds = env.readTextFile("input/UserBehavior.csv");

        //对数据进行处理
        ds.map(new MapFunction<String, UserBehavior>() {
            @Override
            public UserBehavior map(String line) throws Exception {

                //将一行数据封装为一个UserBehavior对象
                String[] lines = line.split(",");
                UserBehavior userBehavior = new UserBehavior(Long.valueOf(lines[0]),
                        Long.valueOf(lines[1]),
                        Integer.valueOf(lines[2]),
                        String.valueOf(lines[3]), Long.valueOf(lines[4]));
                return userBehavior;
            }
        })
                .process(new ProcessFunction<UserBehavior,Long>() {
                    //注意这样写的话就必须只能有一个并行度
                    Long sum = 0L;
                    @Override
                    public void processElement(UserBehavior value, Context ctx, Collector<Long> out) throws Exception {
                        //统计网页访问量，网页就是只要点击进来了一次我就记一次数
                        //对用户行为进行筛选
                        if ("pv".equals(value.getBehavior())){
                            sum++;
                            //打印输出
                            out.collect(sum);
                        }
                    }
                })
                //打印输出
        .print();


        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
